// Copyright 2015 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/// +build ignore

package main

import (
	"flag"
	"html/template"
	"log"
	"net/http"

	"net"

	"gitee.com/lwj8507/nggs/util"
	"github.com/gorilla/websocket"
)

var addr = flag.String("addr", ":8081", "http service address")

// use default options
var upgrader = websocket.Upgrader{
	CheckOrigin: func(_ *http.Request) bool { return true },
}

func echo(w http.ResponseWriter, r *http.Request) {
	c, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Print("upgrade:", err)
		return
	}
	defer c.Close()
	for {
		mt, message, err := c.ReadMessage()
		if err != nil {
			log.Println("read:", err)
			break
		}
		//log.Printf("recv: %s", message)
		err = c.WriteMessage(mt, message)
		if err != nil {
			log.Println("write:", err)
			break
		}
	}
}

func home(w http.ResponseWriter, r *http.Request) {
	homeTemplate.Execute(w, nil)
}

func main() {
	flag.Parse()
	log.SetFlags(0)

	//http.HandleFunc("/echo", echo)
	//http.HandleFunc("/", home)
	//go http.ListenAndServe(*addr, nil)

	mux := http.NewServeMux()
	mux.HandleFunc("/echo", echo)
	mux.HandleFunc("/", home)

	ln, err := net.Listen("tcp", *addr)
	if err != nil {
		log.Panicf("listen [%s] fail, %s", *addr, err)
	}

	httpServer := &http.Server{
		Addr:    *addr,
		Handler: mux,
	}

	go httpServer.Serve(ln)

	util.WaitExitSignal()
}

var homeTemplate = template.Must(template.New("").Parse(`
<!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <script>
        window.addEventListener("load", function(evt) {

            var output = document.getElementById("output");
            var input = document.getElementById("input");
            var addr = document.getElementById("addr")
            var ws;

            var print = function(message) {
                var now = new Date()
                var d = document.createElement("div");
                d.innerHTML = "[" + now.toLocaleString() + "] " + message;
                output.appendChild(d);
            };

            document.getElementById("open").onclick = function(evt) {
                if (ws) {
                    return false;
                }
                ws = new WebSocket("ws://" + addr.value);
                ws.onopen = function(evt) {
                    print("OPEN");
                }
                ws.onclose = function(evt) {
                    print("CLOSE");
                    ws = null;
                }
                ws.onmessage = function(evt) {
                    print("RESPONSE: " + evt.data);
                }
                ws.onerror = function(evt) {
                    print("ERROR: " + evt.data);
                }
                return false;
            };

            document.getElementById("send").onclick = function(evt) {
                if (!ws) {
                    return false;
                }
                print("SEND: " + input.value);
                ws.send(input.value);
                return false;
            };

            document.getElementById("close").onclick = function(evt) {
                if (!ws) {
                    return false;
                }
                ws.close();
                return false;
            };

        });
    </script>
</head>
<body>
<table>
    <tr><td valign="top" width="50%">
        <p>Click "Open" to create a connection to the server,
            "Send" to send a message to the server and "Close" to close the connection.
            You can change the message and send multiple times.
        <p>
            <form>
                <input id="addr" type="text" value="192.168.25.61:8081/echo">
                <button id="open">Open</button>
                <button id="close">Close</button>
        <p>
            <input id="input" type="text" value="Hello world!">
            <button id="send">Send</button>
            </form>
    </td><td valign="top" width="50%">
        <div id="output"></div>
    </td></tr></table>
</body>
</html>
`))
